package com.triplelink.pool;

import java.util.HashMap;
import java.util.Map;

import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.base.RepositoryBase;

import resource.Config;

import com.franz.agraph.repository.AGCatalog;
import com.franz.agraph.repository.AGRepository;
import com.franz.agraph.repository.AGServer;
import com.triplelink.context.Connector;


public class RepositoryPool
{
	private static Map<String, RepositoryBase> REPOSITORIES = new HashMap<String, RepositoryBase>();
	
	public static Connector createConnector()
	{
		return new Connector(getRepositoryBase());
	}
	
	private static RepositoryBase getRepositoryBase ()
	{
		String serverLink = createServerLink(Config.HOST, Config.PORT);
		String repositoryLink = serverLink + Config.REPOSITORY;
		
		RepositoryBase repositoryBase = REPOSITORIES.get(repositoryLink);
		
		if (repositoryBase == null)
		{
			repositoryBase = createRepositoryBase(serverLink, Config.USER, Config.PASS_WORD, Config.REPOSITORY);
			REPOSITORIES.put(repositoryLink, repositoryBase);
		}
		
		return repositoryBase;
	}
	
	private static String createServerLink(String host, String port)
	{
		return "http://" + Config.HOST + ":" + Config.PORT;
	}
	
	private static RepositoryBase createRepositoryBase (String serverLink, String user, String passWord, String repository)
	{
		System.out.print("Conecting to allegro...\n");
		AGServer server = new AGServer(serverLink, user, passWord);
		AGCatalog catalog = server.getRootCatalog();
		AGRepository myRepository = null;
		
		try
		{
			myRepository = catalog.createRepository(repository);
			
			System.out.println("Conecting to allegro OK...\n");
			
		} catch (RepositoryException e) {
			
			e.printStackTrace();
		}
		
		return myRepository;
	}
}
